package com.example.demo.Controller; // 您的 BookkeepingController 包

import com.example.demo.dto.ApiResponse;
import com.example.demo.entity.Bookkeeping;
import com.example.demo.entity.User; // 导入 User
import com.example.demo.service.BookkeepingService;
import com.example.demo.service.UserService; // 导入 UserService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; // 导入 Authentication
import org.springframework.security.core.context.SecurityContextHolder; // 导入 SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails; // 导入 UserDetails
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/bookkeeping")
public class BookkeepingController {

    @Autowired
    private BookkeepingService bookkeepingService;

    @Autowired
    private UserService userService; // 用于通过 account 获取 User 实体

    // 辅助方法：获取当前登录用户的ID
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
            throw new RuntimeException("用户未认证"); // 或者返回特定的未授权响应
        }
        String account; // Spring Security UserDetails 的 username 即我们的 account
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            account = ((UserDetails) principal).getUsername();
        } else {
            account = principal.toString();
        }
        User currentUser = userService.getUserByAccount(account); // 通过 account 获取 User 实体
        return currentUser.getId();
    }

    // 添加记账记录 (不再需要路径中的 userId)
    @PostMapping
    public ResponseEntity<ApiResponse<Bookkeeping>> addRecord(@RequestBody Bookkeeping record) {
        try {
            Integer currentUserId = getCurrentUserId();
            Bookkeeping newRecord = bookkeepingService.addRecord(currentUserId, record);
            return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.created("记账成功", newRecord));
        } catch (RuntimeException e) {
            // 根据异常类型返回更具体的错误码
            if (e.getMessage() != null && e.getMessage().contains("用户未认证")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.unauthorized(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.badRequest(e.getMessage()));
        }
    }

    // 查看当前用户某年某月的记账数据 (不再需要路径中的 userId)
    @GetMapping
    public ResponseEntity<ApiResponse<List<Bookkeeping>>> getRecordsByMonth(
            @RequestParam int year,
            @RequestParam int month) {
        try {
            Integer currentUserId = getCurrentUserId();
            List<Bookkeeping> records = bookkeepingService.getRecordsByUserAndMonth(currentUserId, year, month);
            if (records.isEmpty()) {
                return ResponseEntity.ok(ApiResponse.ok("您在此期间无记账记录", records));
            }
            return ResponseEntity.ok(ApiResponse.ok("查询成功", records));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未认证")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.unauthorized(e.getMessage()));
            }
            // 如果是因为 userService.getUserByAccount 抛出用户未找到 (理论上不应发生，因为已认证)
            // 但为了健壮性，可以处理
            if (e.getMessage() != null && e.getMessage().startsWith("用户未找到")) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.notFound(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.internalServerError(e.getMessage()));
        }
    }

    // 查看当前用户某条记账数据的详情 (不再需要路径中的 userId)
    @GetMapping("/{recordId}")
    public ResponseEntity<ApiResponse<Bookkeeping>> getRecordDetails(@PathVariable Integer recordId) {
        try {
            Integer currentUserId = getCurrentUserId();
            Bookkeeping record = bookkeepingService.getRecordByIdAndUser(recordId, currentUserId);
            return ResponseEntity.ok(ApiResponse.ok("查询详情成功", record));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未认证")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.unauthorized(e.getMessage()));
            }
            // Service 层会抛出 "记账记录未找到或不属于该用户"
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.notFound(e.getMessage()));
        }
    }

    // 修改记账数据 (不再需要路径中的 userId)
    @PutMapping("/{recordId}")
    public ResponseEntity<ApiResponse<Bookkeeping>> updateRecord(
            @PathVariable Integer recordId,
            @RequestBody Bookkeeping recordDetails) {
        try {
            Integer currentUserId = getCurrentUserId();
            Bookkeeping updatedRecord = bookkeepingService.updateRecord(recordId, currentUserId, recordDetails);
            return ResponseEntity.ok(ApiResponse.ok("修改成功", updatedRecord));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未认证")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.unauthorized(e.getMessage()));
            }
            // Service 层会抛出 "记账记录未找到或不属于该用户, 无法更新"
            // 或其他业务校验错误
            if (e.getMessage() != null && (e.getMessage().contains("未找到") || e.getMessage().contains("不属于该用户"))) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.notFound(e.getMessage()));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.badRequest(e.getMessage()));
        }
    }

    // 删除记账数据 (不再需要路径中的 userId)
    @DeleteMapping("/{recordId}")
    public ResponseEntity<ApiResponse<Void>> deleteRecord(@PathVariable Integer recordId) {
        try {
            Integer currentUserId = getCurrentUserId();
            bookkeepingService.deleteRecord(recordId, currentUserId);
            return ResponseEntity.ok(ApiResponse.okMessage("删除成功"));
        } catch (RuntimeException e) {
            if (e.getMessage() != null && e.getMessage().contains("用户未认证")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.unauthorized(e.getMessage()));
            }
            // Service 层会抛出 "记账记录未找到或不属于该用户, 无法删除"
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.notFound(e.getMessage()));
        }
    }
}
